package com.yh.hljapp.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yh.hljapp.AppConfig;
import com.yh.hljapp.AppContext;
import com.yh.hljapp.R;
import com.yh.hljapp.base.BaseFragment;
import com.yh.hljapp.common.TDevice;
import com.yh.hljapp.common.UIHelper;
import com.yh.hljapp.gddb.gbmanager.AddSale_Manager;
import com.yh.hljapp.gddb.gdbean.AddSaleInt_HeadBean;
import com.yh.hljapp.modules.adatper.AddSale_Int_ListAdapter;
import com.yh.hljapp.modules.bean.SimpleBackPage;
import com.yh.hljapp.modules.bean.User;
import com.yh.hljapp.modules.recycleviewutil.SimpleItemTouchHelperCallback;
import com.yh.hljapp.modules.ui.empty.EmptyLayout;
import com.yh.hljapp.modules.widget.RecycleViewDivider;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

import static com.yh.hljapp.R.id.et_earch;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：john
 * <p>
 * 工程：FoodBarcode
 * <p>
 * 文件名：BackMatListFragment
 * <p>
 * 创建时间：2017.06.02.15:30
 * *****************************
 */
public class AddSale_Int_ListFragment extends BaseFragment {

    @InjectView(R.id.recycleview)
    RecyclerView mRecycleview;
    @InjectView(R.id.swiperefreshlayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @InjectView(R.id.error_layout)
    EmptyLayout errorLayout;
    @InjectView(R.id.iv_search)
    ImageView ivSearch;
    @InjectView(et_earch)
    EditText etEarch;
    @InjectView(R.id.img_delete)
    ImageView imgDelete;
    @InjectView(R.id.img_shaixuan)
    ImageView imgShaixuan;
    @InjectView(R.id.ll_search)
    LinearLayout llSearch;
    private List<AddSaleInt_HeadBean> mHeadsByNa;
    private String mName;
    private AddSale_Int_ListAdapter mAdapter;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(AppConfig.SALE_Int_SAVE)) {

                initData();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_cache_list, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        IntentFilter filter = new IntentFilter();
        filter.addAction(AppConfig.SALE_Int_SAVE);
        mActivity.registerReceiver(mReceiver, filter);

        TDevice.hideSoftKeyboard(mActivity);
        mSwipeRefreshLayout.setColorSchemeResources(
                R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // TODO: 2016/8/3 下拉刷新
                if (mSwipeRefreshLayout != null) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
                etEarch.setText("");
                initData();
            }
        });

        imgShaixuan.setOnClickListener(this);
        etEarch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) etEarch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    getActivity()
                                            .getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    getListByKHName();
                    return true;
                }
                return false;
            }
        });
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecycleview.setLayoutManager(layoutManager);
        mRecycleview.addItemDecoration(new RecycleViewDivider(mActivity, LinearLayoutManager.VERTICAL));
    }

    @Override
    public void initData() {
        super.initData();
        User user = AppContext.getInstance().getCurrentUser();
        if (user == null)
            return;
        mName = user.getName();
        if (mName != null) {
            mHeadsByNa = AddSale_Manager.getInstance(mActivity).getHeadsByNa(mName);
        }

        mAdapter = new AddSale_Int_ListAdapter(mActivity, mHeadsByNa, "3");
        if (mHeadsByNa == null || mHeadsByNa.size() == 0) {
            setEmptyLayout();
        }
        mAdapter.setOnItemClickListener(new AddSale_Int_ListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(AddSaleInt_HeadBean head) {
                Bundle bundle = new Bundle();
                bundle.putString("TYPE", "show");
                bundle.putString("ID", head.getId() + "");
                UIHelper.showSimpleBack(mActivity, SimpleBackPage.ADD_SALE_INT, bundle, "产品入库");
            }
        });
        //关联ItemTouchHelper和RecyclerView
        ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(mAdapter);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(mRecycleview);
        mRecycleview.setAdapter(mAdapter);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.img_shaixuan:
                getListByKHName();
                break;
        }
    }

    private void getListByKHName() {
        // 先隐藏键盘
        TDevice.hideSoftKeyboard(mActivity);
        String khName = etEarch.getText().toString().trim();
//        if (!StringUtils.isEmpty(khName)) {
//            mHeadsByNa = MatHeadManager2.getInstance(mActivity).getHeadByKHNa(mName, khName, "3");
//            mAdapter.setDatas(mHeadsByNa);
//            mAdapter.notifyDataSetChanged();
//        }
    }


    @Override
    public void onStart() {
        super.onStart();
        User currentUser = AppContext.getInstance().getCurrentUser();
        if (currentUser != null) {
            String name = currentUser.getName();

            List<AddSaleInt_HeadBean> headsByNa = AddSale_Manager.getInstance(mActivity).getHeadsByNa(name);
            if (headsByNa == null || headsByNa.size() == 0) {
                setEmptyLayout();
            }

            if (mHeadsByNa != null && headsByNa != null) {
                if (mHeadsByNa.size() != headsByNa.size()) {
                    AddSale_Int_ListAdapter backMatListAdapter = new AddSale_Int_ListAdapter(mActivity, headsByNa, "3");
                    backMatListAdapter.setOnItemClickListener(new AddSale_Int_ListAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(AddSaleInt_HeadBean head) {
                            Bundle bundle = new Bundle();
                            bundle.putString("TYPE", "show");
                            bundle.putString("ID", head.getId() + "");
                            UIHelper.showSimpleBack(mActivity, SimpleBackPage.ADD_SALE_INT, bundle, "产品入库");
                        }
                    });
                    mRecycleview.setAdapter(backMatListAdapter);
                }
            }
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户获取失败，请重新登陆!", Snackbar.LENGTH_SHORT).show();
        }
    }

    private void setEmptyLayout() {
        errorLayout.setVisibility(View.VISIBLE);
        errorLayout.setErrorType(EmptyLayout.NODATA);
        errorLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initData();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mActivity.unregisterReceiver(mReceiver);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);

    }
}
